package com.icore.ui;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.icore.AppContext;
import com.icore.AppException;
import com.icore.R;
import com.icore.bean.GoucheBaseInfo;
import com.icore.bean.RetRes;
import com.icore.common.UIHelper;
import com.icore.ui.base.BaseActivity;

/**
 * 购车详情
 * 
 */
public class GoucheDetailActivity extends BaseActivity implements OnCheckedChangeListener {

	private String userID = "";
	private String carNo = "";

	private ImageView editIV;
	private PopupWindow popupWindow;
	private LinearLayout layout;
	private ListView listView;
	private String title[] = { "保存" };

	private RadioGroup mRadioGroup;
	private RadioButton mRadioButton1;
	private RadioButton mRadioButton2;
	private RadioButton mRadioButton3;
	private RadioButton mRadioButton4;
	private ImageView mImageView;
	private float mCurrentCheckedRadioLeft;// 当前被选中的RadioButton距离左侧的距离
	private HorizontalScrollView mHorizontalScrollView;// 上面的水平滚动控件
	private ViewPager mViewPager; // 下方的可横向拖动的控件
	private ArrayList<View> mViews;// 用来存放下方滚动的layout

	// 基本信息
	private View baseinfoView;
	private TextView binoTV;
	private EditText binameET;
	private EditText bicompanyaddrET;
	private EditText bihomeaddrET;
	private EditText biphoneET;

	private View detailView;
	private View fujiaView;
	private View baoxianView;

	/** 请求类型 */
	public int REQ_Type_INT = 0;
	public static final int BASEINFO_QUERY = 1; // 查询基本信息
	public static final int BASEINFO_UPDATE = 2; // 修改基本信息

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gouche_detail_view);

		// 获取传递过来的数据
		getIntentEntra();

		// 返回
		ImageView backIV = (ImageView) findViewById(R.id.backID);
		backIV.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}

		});

		editIV = (ImageView) findViewById(R.id.editID);
		editIV.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int x = getWindowManager().getDefaultDisplay().getWidth() * 2 / 3;
				int y = editIV.getBottom() * 3 / 2;

				showPopupWindow(x, y);
			}

		});

		iniController();
		iniListener();
		iniLayout();
		iniVariable();

		mRadioButton1.setChecked(true);
		mViewPager.setCurrentItem(1);
		mCurrentCheckedRadioLeft = getCurrentCheckedRadioLeft();

		// 初始化基本信息数据
		reqData(BASEINFO_QUERY);
	}

	private void getIntentEntra() {
		Intent intent = getIntent();
		userID = intent.getStringExtra("user_id");
		carNo = intent.getStringExtra("car_no");
	}

	private void iniLayout() {
		// 基本信息
		baseinfoView = getLayoutInflater().inflate(R.layout.gouchebaseinfo_view, null);
		binoTV = (TextView) baseinfoView.findViewById(R.id.baseinfonoTV);
		binameET = (EditText) baseinfoView.findViewById(R.id.baseinfonameET);
		bicompanyaddrET = (EditText) baseinfoView.findViewById(R.id.baseinfocompanyaddrET);
		bihomeaddrET = (EditText) baseinfoView.findViewById(R.id.baseinfohomeaddrET);
		biphoneET = (EditText) baseinfoView.findViewById(R.id.baseinfophoneET);

		// 详细信息
		detailView = getLayoutInflater().inflate(R.layout.gouchedetail_view, null);
		
		// 附加信息
		fujiaView = getLayoutInflater().inflate(R.layout.gouchefujia_view, null);

		// 保险信息
		baoxianView = getLayoutInflater().inflate(R.layout.gouchebaoxian_view, null);
	}

	private void iniController() {
		mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		mRadioButton1 = (RadioButton) findViewById(R.id.btn1);
		mRadioButton2 = (RadioButton) findViewById(R.id.btn2);
		mRadioButton3 = (RadioButton) findViewById(R.id.btn3);
		mRadioButton4 = (RadioButton) findViewById(R.id.btn4);

		mImageView = (ImageView) findViewById(R.id.img1);
		mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
		mViewPager = (ViewPager) findViewById(R.id.pager);
	}

	private void iniListener() {
		mRadioGroup.setOnCheckedChangeListener(this);
		mViewPager.setOnPageChangeListener(new MyPagerOnPageChangeListener());
	}

	private void iniVariable() {
		mViews = new ArrayList<View>();
		mViews.add(getLayoutInflater().inflate(R.layout.blank_view, null));
		mViews.add(baseinfoView);
		mViews.add(detailView);
		mViews.add(fujiaView);
		mViews.add(baoxianView);
		mViews.add(getLayoutInflater().inflate(R.layout.blank_view, null));

		mViewPager.setAdapter(new MyPagerAdapter());// 设置ViewPager的适配器
	}

	/**
	 * RadioGroup点击CheckedChanged监听
	 */
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		AnimationSet _AnimationSet = new AnimationSet(true);
		TranslateAnimation _TranslateAnimation;

		Log.i("zj", "checkedid=" + checkedId);
		if (checkedId == R.id.btn1) {
			_TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft, getResources().getDimension(R.dimen.rdo1), 0f, 0f);
			_AnimationSet.addAnimation(_TranslateAnimation);
			_AnimationSet.setFillBefore(false);
			_AnimationSet.setFillAfter(true);
			_AnimationSet.setDuration(100);

			mImageView.startAnimation(_AnimationSet);// 开始上面蓝色横条图片的动画切换
			mViewPager.setCurrentItem(1);// 让下方ViewPager跟随上面的HorizontalScrollView切换
		} else if (checkedId == R.id.btn2) {
			_TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft, getResources().getDimension(R.dimen.rdo2), 0f, 0f);

			_AnimationSet.addAnimation(_TranslateAnimation);
			_AnimationSet.setFillBefore(false);
			_AnimationSet.setFillAfter(true);
			_AnimationSet.setDuration(100);

			mImageView.startAnimation(_AnimationSet);
			mViewPager.setCurrentItem(2);
		} else if (checkedId == R.id.btn3) {
			_TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft, getResources().getDimension(R.dimen.rdo3), 0f, 0f);

			_AnimationSet.addAnimation(_TranslateAnimation);
			_AnimationSet.setFillBefore(false);
			_AnimationSet.setFillAfter(true);
			_AnimationSet.setDuration(100);

			mImageView.startAnimation(_AnimationSet);
			mViewPager.setCurrentItem(3);
		} else if (checkedId == R.id.btn4) {
			_TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft, getResources().getDimension(R.dimen.rdo4), 0f, 0f);

			_AnimationSet.addAnimation(_TranslateAnimation);
			_AnimationSet.setFillBefore(false);
			_AnimationSet.setFillAfter(true);
			_AnimationSet.setDuration(100);

			mImageView.startAnimation(_AnimationSet);
			mViewPager.setCurrentItem(4);
		}
		mCurrentCheckedRadioLeft = getCurrentCheckedRadioLeft();// 更新当前蓝色横条距离左边的距离
		mHorizontalScrollView.smoothScrollTo((int) mCurrentCheckedRadioLeft - (int) getResources().getDimension(R.dimen.rdo2), 0);
	}

	/**
	 * 获得当前被选中的RadioButton距离左侧的距离
	 */
	private float getCurrentCheckedRadioLeft() {
		if (mRadioButton1.isChecked()) {
			return getResources().getDimension(R.dimen.rdo1);
		} else if (mRadioButton2.isChecked()) {
			return getResources().getDimension(R.dimen.rdo2);
		} else if (mRadioButton3.isChecked()) {
			return getResources().getDimension(R.dimen.rdo3);
		} else if (mRadioButton4.isChecked()) {
			return getResources().getDimension(R.dimen.rdo4);
		}
		return 0f;
	}

	/**
	 * ViewPager的适配器
	 */
	private class MyPagerAdapter extends PagerAdapter {

		@Override
		public void destroyItem(View v, int position, Object obj) {
			((ViewPager) v).removeView(mViews.get(position));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mViews.size();
		}

		@Override
		public Object instantiateItem(View v, int position) {
			((ViewPager) v).addView(mViews.get(position));
			return mViews.get(position);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

	}

	/**
	 * ViewPager的PageChangeListener(页面改变的监听器)
	 */
	private class MyPagerOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		/**
		 * 滑动ViewPager的时候,让上方的HorizontalScrollView自动切换
		 */
		@Override
		public void onPageSelected(int position) {
			if (position == 0) {
				mViewPager.setCurrentItem(1);
			} else if (position == 1) {
				mRadioButton1.performClick();
			} else if (position == 2) {
				mRadioButton2.performClick();
			} else if (position == 3) {
				mRadioButton3.performClick();
			} else if (position == 4) {
				mRadioButton4.performClick();
			} else if (position == 5) {
				mViewPager.setCurrentItem(4);
			}
		}
	}

	public void showPopupWindow(int x, int y) {
		layout = (LinearLayout) LayoutInflater.from(GoucheDetailActivity.this).inflate(R.layout.pop_group, null);
		listView = (ListView) layout.findViewById(R.id.lv_dialog);
		listView.setAdapter(new ArrayAdapter<String>(GoucheDetailActivity.this, R.layout.pop_item, R.id.tv_text, title));

		popupWindow = new PopupWindow(GoucheDetailActivity.this);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 3);
		popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setContentView(layout);
		popupWindow.showAtLocation(findViewById(R.id.titleBarRL), Gravity.LEFT | Gravity.TOP, x, y + 5);// 需要指定Gravity，默认情况是center.

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				popupWindow.dismiss();
				popupWindow = null;

				// 1. 保存
				reqData(BASEINFO_UPDATE);
			}
		});
	}

	private ProgressDialog mProgress;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (mProgress != null) {
				mProgress.dismiss();
			}
			if (msg.what == 1) {
				int code = 0;
				String resMsg = "";

				switch (REQ_Type_INT) {
				case BASEINFO_QUERY:
					GoucheBaseInfo baseinfo = (GoucheBaseInfo) msg.obj;
					code = baseinfo.getResCode();
					resMsg = baseinfo.getResMessage();

					// 失败，弹出提示框
					if (code == 0) {
						UIHelper.ToastMessage(GoucheDetailActivity.this, resMsg);
					}
					// 成功
					else if (code == 1) {
						// 回显
						binoTV.setText(baseinfo.getCarNo());
						binameET.setText(baseinfo.getCustomerName());
						bicompanyaddrET.setText(baseinfo.getCustomerCompanyAddr());
						bihomeaddrET.setText(baseinfo.getCustomerHomeAddr());
						biphoneET.setText(baseinfo.getCustomerPhone());
					}
					break;
				case BASEINFO_UPDATE:
					RetRes retRes = (RetRes) msg.obj;
					code = retRes.getResCode();
					resMsg = retRes.getResMessage();

					// 失败，弹出提示框
					if (code == 0) {
						UIHelper.ToastMessage(GoucheDetailActivity.this, resMsg);
					}
					// 成功
					else if (code == 1) {
						UIHelper.startActivity(GoucheDetailActivity.this, GoucheListActivity.class, new BasicNameValuePair("user_id",
								userID));
					}
					break;
				}
			} else {
				((AppException) msg.obj).makeToast(GoucheDetailActivity.this);
			}
		}
	};

	private void reqData(int reqType) {
		REQ_Type_INT = reqType;
		mProgress = ProgressDialog.show(GoucheDetailActivity.this, null, "加载中...", true, true);

		new Thread() {

			@Override
			public void run() {
				Message msg = new Message();
				Map<String, Object> params = new HashMap<String, Object>();
				try {
					switch (REQ_Type_INT) {
					case BASEINFO_QUERY:
						params.put("car_no", carNo);

						GoucheBaseInfo baseinfo = AppContext.server.queryBI(params);
						msg.what = 1;
						msg.obj = baseinfo;
						break;
					case BASEINFO_UPDATE:
						params.put("user_id", userID);
						params.put("name", URLEncoder.encode(binameET.getText().toString()));
						params.put("company", URLEncoder.encode(bicompanyaddrET.getText().toString()));
						params.put("home", URLEncoder.encode(bihomeaddrET.getText().toString()));
						params.put("phone", URLEncoder.encode(biphoneET.getText().toString()));

						RetRes retRes = AppContext.server.insertBI(params);
						msg.what = 1;
						msg.obj = retRes;
						break;
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
}